import { Component } from "@angular/core";
import {
  IonicPage,
  NavController,
  NavParams,
  ViewController,
  AlertController
} from "ionic-angular";
import { QRScanner, QRScannerStatus } from "@ionic-native/qr-scanner";

import { UserService } from "./../../../providers/UserService";
import { StorageService } from "./../../../providers/StorageService";
import { hasPointerMoved } from "ionic-angular/util/dom";
/**
 * Generated class for the ScanPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: "page-scan",
  templateUrl: "scan.html"
})
export class ScanPage {
  screenHeight: any;
  marginTop: any;
  light: boolean; //判断闪光灯
  frontCamera: boolean; //判断摄像头

  userinfo: any;
  showWritecode: boolean;
  showScanner: boolean;
  /**美甲师扫码参数 */
  artistVo = {
    artist_id: null,
    code: ""
  };
  /**美甲店主扫码参数 */
  shopVO = {
    shop_id: null,
    code: ""
  };
  /**输入劵码 */
  inpuPayCode = {
    pay_code: null,
    user_id: null,
    artist_id: null
  };
  Scan;
  Scan2;
  constructor(
    private navCtrl: NavController,
    private navParams: NavParams,
    private alertCtrl: AlertController,
    private qrScanner: QRScanner,
    public stc: StorageService,
    public userService: UserService,
    private viewCtrl: ViewController
  ) {
    //默认为false
    this.light = false;
    this.frontCamera = false;
    this.userinfo = this.stc.read("userinfo");
    this.inpuPayCode.user_id = this.userinfo.user_id;
    this.inpuPayCode.artist_id = this.userinfo.artist_id;
    console.log(this.inpuPayCode);
    console.log(this.userinfo);
    console.log(this.userinfo["user_type"].indexOf(2) != -1);
  }

  ionViewDidLoad() {
    this.screenHeight = screen.height;
    let num = this.screenHeight;
    this.marginTop = parseInt(num) * 0.4 + "px";
    console.log(this.screenHeight + "和" + this.marginTop);
    this.screenHeight = parseInt(num) + "px";

    this.showCamera();
    this.showScan();
    this.qrScanner
      .prepare()
      .then((status: QRScannerStatus) => {
        if (status.authorized) {
          // camera permission was granted
          // start scanning
          let scanSub = this.qrScanner.scan().subscribe((text: string) => {
            // alert(text);
            this.getCode(text);
            // this.qrScanner.hide(); // hide camera preview
            scanSub.unsubscribe(); // stop scanning

            // this.navCtrl.pop();
          });

          // show camera preview
          this.qrScanner.show();

          // wait for user to scan something, then the observable callback will be called
        } else if (status.denied) {
          // camera permission was permanently denied
          // you must use QRScanner.openSettings() method to guide the user to the settings page
          // then they can grant the permission from there
        } else {
          // permission was denied, but not permanently. You can ask for permission again at a later time.
        }
      })
      .catch((e: any) => console.log("Error is", e));
  }

  ionViewDidEnter() {
    //页面可见时才执行
    // this.showCamera();
    // this.showScan();
    let content = this.viewCtrl.getContent();
    console.log(content);
    console.log(content._viewCtrlReadSub.closed);
    if (content._viewCtrlReadSub.closed == null) {
      console.log("content123");
      content._viewCtrlReadSub.closed = true;
      content._viewCtrlWriteSub.closed = true;
    }
    console.log(document.getElementById("chartContainer"));
    console.log(this.viewCtrl.hasNavbar());
    let pageREF = this.viewCtrl.pageRef();
    console.log(pageREF);
  }

  ionViewWillEnter() {
    //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
    //Add 'implements AfterViewInit' to the class.

    let lg= document.getElementsByTagName("page-tabs").length;
    // console.log(this.Scan = document.getElementsByTagName("page-tabs"))
    
    let wel= document.getElementsByTagName("ion-modal")
    console.log(wel);
    let wellg=document.getElementsByTagName("page-welcome").length;
    if (wellg==1) {
      this.Scan= document.getElementsByTagName("ng-component")[0];
      console.log(this.Scan);
      this.Scan.style.display = "none";
     }
 
    if (lg ==2) {
     this.Scan= document.getElementsByTagName("ng-component")[0];
     console.log(this.Scan);
     this.Scan.style.display = "none";
    }
    // if (lg ==1) {
    //   this.Scan= document.getElementsByTagName("ng-component")[0];
    //   console.log(this.Scan);
    //   this.Scan.style.display = "none";
    //  }
  } 
   ionViewDidLeave() {
    //离开页面
    // this.showCamera();
    // this.showScan();
    // this.navCtrl.pop({"animate":false});
    let lg= document.getElementsByTagName("page-tabs").length;
    if (lg ==2) {
    this.Scan.style.display = "block"
    }
    let wellg=document.getElementsByTagName("page-welcome").length;
    if (wellg==1) {
      this.Scan= document.getElementsByTagName("ng-component")[0];
      console.log(this.Scan);
      this.Scan.style.display = "block";
     }
  }
  // ionViewWillUnload() {
  //   this.Scan2 = document.getElementsByTagName(
  //     "ng-component"
  //   )[0] as HTMLDivElement;
  //   this.Scan2.style.display = "block";
  //   console.log(this.Scan2);
  // }
  /**获取二维码信息并发送请求 */
  async getCode(text) {
    if (
      this.userinfo["user_type"].indexOf(3) != -1 &&
      this.userinfo["user_type"].indexOf(2) != -1
    ) {
      console.log("我是美甲店主也是美甲师");
      this.shopVO.shop_id = this.userinfo.shop_id;
      this.shopVO.code = text;

      console.log(this.shopVO);
      let res = await this.userService.getQrCodeAPI(this.shopVO);
      console.log(res);
      // if (res.code == 1) {
      let alert = this.alertCtrl.create({
        subTitle: res.msg,
        buttons: [
          {
            text: "OK",
            handler: data => {
              console.log(this.navCtrl);
              this.navCtrl.pop({ animate: false });
              // this.navCtrl.swipeBackEnabled;
              // alert(this.navCtrl.canSwipeBack());
            }
          }
        ]
      });
      alert.present();
      // }
      return;
    } else if (this.userinfo["user_type"].indexOf(2) != -1) {
      console.log("我是美甲师");
      this.artistVo.artist_id = this.userinfo.artist_id;
      this.artistVo.code = text;
      console.log(this.artistVo);
      let res = await this.userService.getQrCodeAPI(this.artistVo);
      console.log(res);
      // if (res.code == 1) {
      let alert = this.alertCtrl.create({
        subTitle: res.msg,
        buttons: [
          {
            text: "OK",
            handler: data => {
              this.navCtrl.pop({ animate: false });
            }
          }
        ]
      });
      alert.present();
      // }
      return;
    } else if (this.userinfo["user_type"].indexOf(3) != -1) {
      console.log("我是美甲店主");
      this.shopVO.shop_id = this.userinfo.shop_id;
      this.shopVO.code = text;

      console.log(this.shopVO);
      let res = await this.userService.getQrCodeAPI(this.shopVO);
      console.log(res);
      // if (res.code == 1) {
      let alert = this.alertCtrl.create({
        subTitle: res.msg,
        buttons: [
          {
            text: "OK",
            handler: data => {
              this.navCtrl.pop({ animate: false });
            }
          }
        ]
      });
      alert.present();
      // }

      return;
    }
  }
  cancelAnimate() {
    this.navCtrl.pop({ animate: false });
  }
  /**店主输入付款码接口 */
  async inputPayCodeAPI(event) {
    let reg = /^[0-9]\d{7}$/;
    if (this.inpuPayCode.pay_code.trim().length == 8) {
      console.log(reg.test(this.inpuPayCode.pay_code.trim()));
      if (reg.test(this.inpuPayCode.pay_code.trim())) {
        let res = await this.userService.inputPayCodeAPI(this.inpuPayCode);
        console.log(res);
        let alert = this.alertCtrl
          .create({
            subTitle: res.msg,
            buttons: [
              {
                text: "确定",
                handler: data => {
                  // console.log(this.navCtrl.pop({"animate":false}));
                  this.navCtrl.pop({ animate: false });
                }
              }
            ]
          })
          .present();
        return;
      } else {
        let alert = this.alertCtrl
          .create({
            subTitle: "请输入正确的8位数消费劵码",
            buttons: [
              {
                text: "确定",
                handler: data => {
                  // this.inpuPayCode.pay_code = null;
                }
              }
            ]
          })
          .present();
        return;
      }
    }
  }

  /** 显示扫描 */
  showScan() {
    this.showCamera();
    this.qrScanner.show();
    this.showScanner = true;
    this.showWritecode = false;
  }
  /**显示输入劵码 */
  showWriteCode() {
    this.hideCamera();
    this.showScanner = false;
    this.showWritecode = true;
  }

  /**
   * 闪光灯控制，默认关闭
   */
  // toggleLight() {
  //   if (this.light) {
  //     this.qrScanner.disableLight();
  //   } else {
  //     this.qrScanner.enableLight();
  //   }
  //   this.light = !this.light;
  // }

  // /**
  //  * 前后摄像头互换
  //  */
  // toggleCamera() {
  //   if (this.frontCamera) {
  //     this.qrScanner.useBackCamera();
  //   } else {
  //     this.qrScanner.useFrontCamera();
  //   }
  //   this.frontCamera = !this.frontCamera;
  // }

  showCamera() {
    (window.document.querySelector("ion-app") as HTMLElement).classList.add(
      "cameraView"
    );
  }
  hideCamera() {
    this.qrScanner.hide(); //需要关闭扫描，否则相机一直开着
    (window.document.querySelector("ion-app") as HTMLElement).classList.remove(
      "cameraView"
    );
  }

  ionViewWillLeave() {
    this.hideCamera();
  }
}
